package com.example.controller;


import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.common.AliPayConfig;
import com.example.common.AuthAccess;
import com.example.pojo.entity.Order;
import com.example.service.OrderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;



import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    // 支付宝沙箱网关地址

    //    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig alipayConfig;
    @Resource
    private OrderService orderService;

    private static final Logger logger = LoggerFactory.getLogger(AliPayController.class);

    @AuthAccess
    @GetMapping("/pay")
    public void pay(@RequestParam  String orderNo, HttpServletResponse httpResponse) throws Exception{
        // 根据订单号查询订单
        Order order = orderService.getByOrderNum(orderNo);
        if (order == null){
            return;
        }
        //1.创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient= new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),FORMAT,CHARSET,alipayConfig.getAlipayPublicKey(),SIGN_TYPE);
        //2.创建Request并设置Request参数
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent=new JSONObject();
        bizContent.set("out_trade_no",order.getOrderNum());         // 商户订单号，需要保证不重复
        bizContent.set("total_amount",order.getPrice());            // 订单总金额，单位为元，精确到小数点后两位
        bizContent.set("subject",order.getGoodsName());             // 订单标题
        bizContent.set("product_code","FAST_INSTANT_TRADE_PAY");    // 销售产品码，不传默认为FAST_INSTANT_TRADE_PAY  固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:5173/shoppingCar");         // 支付成功后跳转的页面

        //3.Client通过response给前台页面返回结果
        String form="";
        try {
            form=alipayClient.pageExecute(request).getBody();
        }catch (AlipayApiException e){
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" +CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @AuthAccess
    @PostMapping("/notify")
    public  void payNotify(HttpServletRequest request) throws Exception{
        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("======支付宝异步回调======");
            Map<String,String> params =new HashMap<>();
            Map<String,String[]>requestParams =request.getParameterMap();
            for (String name:requestParams.keySet()){
                params.put(name,request.getParameter(name));
            }
            String sign=params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature =AlipaySignature.rsa256CheckContent(content,sign,alipayConfig.getAlipayPublicKey(),"UTF-8");
            if (checkSignature){
                System.out.println("交易名称："+params.get("subject"));
                System.out.println("交易状态："+params.get("trade_status"));
                System.out.println("支付宝交易凭证："+params.get("trade_no"));
                System.out.println("商家订单号："+params.get("out_trade_no"));
                System.out.println("交易金额："+params.get("total_amount"));
                System.out.println("买家在支付宝的唯一id："+params.get("buyer_id"));
                System.out.println("买家付款时间："+params.get("gmt_payment"));
                System.out.println("买家付款金额："+params.get("buyer_pay_amount"));


                String orderNum =params.get("out_trade_no");        //订单号
                String payment =params.get("gmt_payment");          //支付时间
                String alipayTradeNo =params.get("trade_no");       //支付宝交易号
                Order order=orderService.getByOrderNum(orderNum);       //根据订单号查询订单

                order.setOrderState(true);
                order.setPayTime(payment);
                order.setPayNum(alipayTradeNo);
                orderService.updateOrder(order);
            }
        }
    }
}